package edu.bit.water.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import edu.bit.water.entity.Column;
import edu.bit.water.entity.MetaWater;
import edu.bit.water.service.MetaWaterAssociationService;
import edu.bit.water.service.MetaWaterService;

/**
 * @author YYF
 *
 */
@Controller
@RequestMapping("/meta_water")
public class MetaWaterController {

	@Autowired
	private MetaWaterService metaWaterService;
	@Autowired
	private MetaWaterAssociationService metaWaterAssociationService;

	/**
	 ** 查询元数据表
	 **
	 * @return Map<String, Object> 如果查询成功则success为true,并返回metaWaterList
	 *         如果失败则返回false,errMsg中为结果
	 */
	@ResponseBody
	@RequestMapping(value = "/select", method = RequestMethod.GET)
	public Map<String, Object> queryMataWater() {
		Map<String, Object> modelMap = new HashMap<>();
		List<MetaWater> metaWaterList = new ArrayList<MetaWater>();
		try {
			metaWaterList = metaWaterService.queryMetaWater();
			modelMap.put("status", "success");
			modelMap.put("rows", metaWaterList);
		} catch (Exception e) {
			modelMap.put("status", "failed");
			modelMap.put("msg", e.getMessage());
		}
		return modelMap;
	}


	/**查询水表数值字段
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectcolumncount", method = RequestMethod.GET)
	public List<Map<String, String>> queryMetaWaterColumn() {
		List<Map<String, String>> fields = new ArrayList<>();
		Map<String, String> field = new HashMap<>();
		for (Column column : metaWaterService.selectColumnCount()) {
			field = new HashMap<>();
			field.put("enName", column.enName);
			field.put("csName", column.csName);
			fields.add(field);
		}
		return fields;
	}

	/**
	 *
	 * @param metaWater 元数据设备表实体类
	 * @return 成功返回1，失败返回0
	 */
	@ResponseBody
	@RequestMapping("/insert")
	public Map<String, Object> insert(MetaWater metaWater) {
		MetaWater temp = metaWater;
		temp.setDataType(temp.getDataType().toUpperCase());
		return metaWaterService.insertMetaWater(temp);
	}

	/**
	 *
	 * 默认需要删除的数据均存在与实体表与元数据表里面 对于因需要删除的数据不在表中而抛出的异常未作处理
	 *
	 * @param metaWater 元数据设备表实体类
	 * @return Map
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(@RequestBody List<String> enNames) {
		MetaWater metaWater = new MetaWater();
		Map<String, Object> modelMap = new HashMap<>();
		for (int i = 0; i < enNames.size(); i++) {
			metaWaterService.deleteMetaWater(enNames.get(i));
			metaWater.setEnName(enNames.get(i));
			metaWaterAssociationService.deleteMetaWaterAssociation(metaWater);
			modelMap.put("status", "success");
		}
		return modelMap;
	}

}
